using System;
using System.Collections.Generic;
using System.Text;

namespace Pricom.Controls
{
  class RichTextBox : System.Windows.Forms.RichTextBox
  {
    public void SetText(string s)
    {
      if (InvokeRequired)
        BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate() { AppendText(s); }));
      else
      {
        base.Text = "";
        ClearCache();
        if (!IsHandleCreated)
          Cache(s);
        else
        {
          base.Text = s;
          text = s;
        }
      }
    }

    public new void ScrollToCaret()
    {
      if (InvokeRequired)
        BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate() { ScrollToCaret(); }));
      else
      {
        if (!IsHandleCreated)
          scrollToCaretAfterCreated = true;
        else
          base.ScrollToCaret();
      }
    }

    public new void Clear()
    {
      ClearCache();
      text = string.Empty;
      base.Clear();
    }

    public new void AppendText(string s)
    {
      if (InvokeRequired)
        BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate() { AppendText(s); }));
      else
      {
        if (!IsHandleCreated)
          Cache(s);
        else
        {
          FlushCache();
          base.AppendText(s);
          text += s;
        }
      }
    }
    
    protected override void OnHandleCreated(EventArgs e)
    {
      base.OnHandleCreated(e);
      FlushCache();
      if ( scrollToCaretAfterCreated )
        base.ScrollToCaret();
      scrollToCaretAfterCreated = false;
    }

    private void ClearCache()
    {
      cache.Clear();
    }

    private void FlushCache()
    {
      foreach (string cached in cache)
      {
        base.AppendText(cached);
        text += cached;
      }
      ClearCache();
    }

    private void Cache(string s)
    {
      cache.Add(s);
    }

    private string GetFullCache()
    {
      string s = string.Empty;
      foreach (string cached in cache)
        s += cached;
      return s;
    }

    public new string Text
    {
      get { return text + GetFullCache(); }
      set { SetText(value); }
    }

    private string text = string.Empty;
    private List<string> cache = new List<string>();
    private bool scrollToCaretAfterCreated = false;
  }
}
